import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.ScrollPane;
import java.awt.Window;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import javax.swing.AbstractCellEditor;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.SwingConstants;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;


public class RegisterCourse extends JFrame {

	private JPanel contentPane;
	private JTable table = new JTable();
	
    static String user;
    String check="";
	/**
	 * Launch the application.
	 */
	

	/**
	 * Create the frame.
	 */
	public RegisterCourse(final String user) {
		table.setBounds(23, 200, 900, 400);
		getContentPane().setBackground(Color.ORANGE);
		getContentPane().setLayout(null);
		this.user = user;
		setBackground(Color.ORANGE);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 700, 900);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		final JLabel dept = new JLabel("\n");
		dept.setBounds(113, 58, 221, 16);
		contentPane.add(dept);
		JLabel lblNewLabel_5 = new JLabel("");
		lblNewLabel_5.setIcon(new ImageIcon(LogIn.class.getResource("/resources/p-331002-georgia-tech-yellow-jackets-black-spare-tire-cover-jt-2324558420.jpg")));
		lblNewLabel_5.setBounds(600, 5, 201, 164);
		getContentPane().add(lblNewLabel_5);
		contentPane.add(table);
		final JComboBox comboBox = new JComboBox();
		
		
		comboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
					try{
						Connection conn = Connect.getConnection();
						Statement statt =conn.createStatement();
						
						
						ResultSet ret = statt.executeQuery("SELECT CRN, S.Course_Title, Code, Letter, F.Name, Days,Time, Location FROM SECTION AS S, CRS_CODE AS C, FACULTY AS F, OFFERS AS O, DEPT AS D WHERE   S.Course_Title=O.Course_Title AND S.Instructor_Username=F.Username  AND C.Course_Title=S.Course_Title AND S.Term= '"+ comboBox.getSelectedItem().toString()+"' AND D.Name='"+ dept.getText() + "' AND Code LIKE '"+check +"' GROUP BY S.Course_Title,Letter");
						ResultSetMetaData metaData = ret.getMetaData();	
						int numberOfColumns = metaData.getColumnCount();
						
						String[] columns = {"Select",
				                "CRN",
				                "Title",
				                "Course Code",
				                "Section","Instructor","Days","Time","Location","Mode of Grading"};
						
						int r=0;
						ArrayList<Object[]> ro = new ArrayList<Object[]>();
						while(ret.next()){
							
							Object[] newRow = new Object[numberOfColumns +2];
						
							newRow[0]=new Boolean(false);
							newRow[numberOfColumns+1]=new Boolean(false);
							

			                for (int i = 1; i <= numberOfColumns; i++) {
			                	 
			                    newRow[i]=ret.getObject(i);
			                    
			                }
			                ro.add(newRow);
			               r++; 
			               
			                
							}
						Object[][] rows = new Object[r][numberOfColumns+2];
						
						for(int i=0;i<r;i++){
							
							rows[i]= ro.get(i);
						}
						
						MyTableModel model=new MyTableModel(rows, columns);
							
								
						contentPane.remove(table);
								       
						table = new JTable(model);
						table.getColumnModel().getColumn(0).setCellEditor(new CheckBoxCellEditor());  
						
								
						//table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
						table.setBounds(23, 200, 900, 400);
						
						;
								
						TableColumn column = null;
						for (int i=0;i<numberOfColumns+2;i++){
							column = table.getColumnModel().getColumn(i);
							column.setWidth(200);	
						}
						column = table.getColumnModel().getColumn(2);
						column.setWidth(250);
						
						
						
						///
						contentPane.add(table);
						refresh();
			        
					
					
				conn.close();	
				}catch(Exception e){
					JOptionPane.showMessageDialog(contentPane,"Check Connection");	
				}
				
				}
			});
			
		comboBox.setModel(new DefaultComboBoxModel(new String[] {"", "Fall 2011", "Spring 2012", "Fall 2012", "Spring 2013"}));
		comboBox.setBounds(74, 26, 183, 27);
		contentPane.add(comboBox);
		
		
		//jTable1.setModel(DbUtils.resultSetToTableModel(rs));
		
		
		try{
			Connection con = Connect.getConnection();
			Statement stat =con.createStatement();
			ResultSet dep = stat.executeQuery("SELECT S.Major FROM STUDENT AS S WHERE S.Username='" + user +"'");
			while(dep.next()){
			dept.setText(dep.getString(1));
			}
			if(dept.getText().equals("Biomedical Engineering")){
				check="BME%";
			}
			else if(dept.getText().equals("Electrical & Computer Engineering")){
				check="ECE%";
			}
			else if(dept.getText().equals("Biology")){
				check="BIO%";
			}
			else if(dept.getText().equals("Computer Science")){
				check="CS%";
			}
			else if(dept.getText().equals("Aerospace Engineering")){
				check="AE%";
			}
			con.close();
		}catch(Exception e){
			JOptionPane.showMessageDialog(contentPane,"Check Connection");	
		}
		
		
		JLabel lblTerm = new JLabel("Term:");
		lblTerm.setBounds(23, 30, 61, 16);
		contentPane.add(lblTerm);
		
		JLabel lblDepartment = new JLabel("Department:");
		lblDepartment.setBounds(23, 58, 78, 16);
		contentPane.add(lblDepartment);
		
		JButton btnRegister = new JButton("Register");
		btnRegister.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				int[] rows= table.getSelectedRows();
				int r= table.getRowCount();
				
				
				if(rows.length !=0){
					try{
						Connection co = Connect.getConnection();
						Statement statement =co.createStatement();
						//for(int i =0;i<rows.length;i++){
							String grade ="";
							if(table.getValueAt(rows[0], 9).toString().equals("false")){
								grade="GRADE";
			
		}else{
			grade="PASS/FAIL";
		}
							ArrayList<String> rcourse=new ArrayList<String>();
							ResultSet rs=statement.executeQuery("SELECT Course_Title FROM SECTION AS S,REGISTERS AS R WHERE R.Section_CRN=S.CRN AND R.Student_Username='"+user+"'");
							while(rs.next()){
								rcourse.add(rs.getString(1));
							}
							
							String c="";
							
							rs=statement.executeQuery("SELECT Course_Title FROM SECTION AS S,REGISTERS AS R WHERE S.CRN='"+table.getValueAt(rows[0], 1)+"' AND R.Student_Username='"+user+"'");
							if(rs.next()){
								c=rs.getString(1);
							}
							Boolean ch=false;
							
							for(int v=0;v<rcourse.size();v++){
								if(c.equals(rcourse.get(v))){
									
									ch=true;
								}
							}
							
								if(!ch){
							
							statement.executeUpdate("INSERT INTO REGISTERS(Student_Username,Section_CRN,Grade_Mode) VALUES('" + user + "','" + table.getValueAt(rows[0], 1) +"','"+grade+"')");
							JOptionPane.showMessageDialog(contentPane,"You have successfully registered for "+table.getValueAt(rows[0], 2)+"\n You can continue to register more courses or View Registered course");
								
								}
								else{
									JOptionPane.showMessageDialog(contentPane,"You are already registerd for "+ c +"\n Delete the registered course if you would like to register for a different section.");
								}
							//}co.closE(
								co.close();
					}catch(Exception e){
						JOptionPane.showMessageDialog(contentPane,"Check Connection");
					}
				}
			}
		});
		btnRegister.setBounds(471, 25, 117, 29);
		contentPane.add(btnRegister);
		
		JButton btnViewRegisteredCourses = new JButton("View Registered Courses");
		btnViewRegisteredCourses.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try{
				Connection coon = Connect.getConnection();
				Statement statement =coon.createStatement();
				String out = "You have registered for:\n";
				
				ResultSet result = statement.executeQuery("SELECT Code,C.Course_Title,Letter,Grade_Mode,Term FROM CRS_CODE AS C,SECTION AS S, REGISTERS AS R WHERE C.Course_Title=S.Course_Title AND S.CRN=R.Section_CRN AND R.Student_Username='"+user +"' AND Code LIKE '"+check +"' GROUP BY Letter,Course_Title");
				while(result.next()){
					out+="\n";
					out+="Code: " + result.getString(1) +"\n";
					out+="Title: " + result.getString(2) + "\n";
					out+="Section: " + result.getString(3) + "\n";
					out+="Mode Of grading: " + result.getString(4) + "\n";
					out+="Term: " + result.getString(5) + "\n";
					out+="\n";
				}
				JOptionPane.showMessageDialog(null,out);
				coon.close();
				}catch(Exception e){
					JOptionPane.showMessageDialog(contentPane,"Check Connection");	
				}finally{
					
				}
			}
		});
		btnViewRegisteredCourses.setBounds(396, 58, 192, 29);
		contentPane.add(btnViewRegisteredCourses);
		
		JButton btnStudentServices = new JButton("Student Services");
		btnStudentServices.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
				new StudentServices(user);
			}
		});
		btnStudentServices.setBounds(396, 99, 192, 29);
		contentPane.add(btnStudentServices);
		
		JLabel lblSelect = new JLabel("Select");
		lblSelect.setBounds(57, 170, 44, 16);
		contentPane.add(lblSelect);
		
		JLabel lblCrn = new JLabel("CRN");
		lblCrn.setBounds(125, 170, 35, 16);
		contentPane.add(lblCrn);
		
		JLabel lblCourseTitle = new JLabel("Course Title");
		lblCourseTitle.setBounds(211, 170, 84, 16);
		contentPane.add(lblCourseTitle);
		
		JLabel lblCourseCode = new JLabel("Course Code");
		lblCourseCode.setBounds(292, 170, 84, 16);
		contentPane.add(lblCourseCode);
		
		JLabel lblSection = new JLabel("Section");
		lblSection.setBounds(388, 170, 55, 16);
		contentPane.add(lblSection);
		
		JLabel lblInstructor = new JLabel("Instructor");
		lblInstructor.setBounds(492, 170, 78, 16);
		contentPane.add(lblInstructor);
		
		JLabel lblDays = new JLabel("Days");
		lblDays.setBounds(568, 172, 44, 16);
		contentPane.add(lblDays);
		
		JLabel lblTime = new JLabel("Time");
		lblTime.setBounds(653, 170, 61, 16);
		contentPane.add(lblTime);
		
		JLabel lblLocation = new JLabel("Location");
		lblLocation.setBounds(758, 170, 61, 16);
		contentPane.add(lblLocation);
		
		JLabel lblPassfail = new JLabel("PASS/FAIL");
		lblPassfail.setBounds(842, 170, 64, 16);
		contentPane.add(lblPassfail);
		
		JButton btnDeleteARegistered = new JButton("Delete a Registered Course");
		btnDeleteARegistered.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try{
					Connection con = Connect.getConnection();
					Statement stat=con.createStatement();
					ArrayList<String> crs = new ArrayList<String>();
					ResultSet rs = stat.executeQuery("SELECT R.Section_CRN,Code,C.Course_Title,Letter FROM CRS_CODE AS C,SECTION AS S, REGISTERS AS R WHERE C.Course_Title=S.Course_Title AND S.CRN=R.Section_CRN AND R.Student_Username='"+user +"' AND Code LIKE '"+check +"' GROUP BY Letter,Course_Title");
					while(rs.next()){
						crs.add(rs.getString(1) +","+rs.getString(3) + ",Section: "+ rs.getString(4));
					}
				String[] crsa=new String[crs.size()];
				for(int i=0;i<crs.size();i++){
					crsa[i]=crs.get(i);
				}
				Icon icon=new ImageIcon(LogIn.class.getResource("/resources/p-331002-georgia-tech-yellow-jackets-black-spare-tire-cover-jt-2324558420.jpg"));
				String s = (String)JOptionPane.showInputDialog(contentPane, "Select the course you will like to delete:\n", "Delete Course",JOptionPane.PLAIN_MESSAGE,icon,crsa,crs.get(1));
				if(s!=null){
					String[] list =  s.split(",");
					stat.executeUpdate("DELETE FROM REGISTERS WHERE Section_CRN='"+list[0]+"' AND Student_Username='" + user +"'");
					JOptionPane.showMessageDialog(contentPane,"You have successfully deleted "+ s);
				con.close();
				}
				}catch(Exception e){
					JOptionPane.showMessageDialog(contentPane,"Check Connection");	
				}
			}
		});
		btnDeleteARegistered.setBounds(375, 129, 213, 29);
		contentPane.add(btnDeleteARegistered);
		
		
		
		
		setPreferredSize(new Dimension(1200, 500));
		pack();
		setVisible(true);
		setTitle("Register for Courses");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		
	}
	public void refresh()
	
    {
		
        getRootPane().validate();
        getRootPane().repaint();
        this.pack();
    }
	private class MyTableModel extends AbstractTableModel {  
		   
		private Object[][] data;  
		private Object[] columns;  
		   
		public MyTableModel(Object[][] data, Object[] columns)  {  
		this.data = data;  
		this.columns = columns;  
		}  
		   
		public Class getColumnClass(int columnIndex) {  
			if (columnIndex ==0 || columnIndex==9){
				return data[0][columnIndex].getClass();  
		
			}
			else{
				return new DefaultTableModel().getColumnClass(columnIndex);  
			}
		}  
		public int getColumnCount() {  
		return columns.length;  
		}  
		public int getRowCount() {  
		return data.length;  
		}  
		public Object getValueAt(int rowIndex, int columnIndex) {  
		return data[rowIndex][columnIndex];  
		} 
		public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
//		    if (columnIndex == 0 || columnIndex ==9) {
//		        data[rowIndex][columnIndex] = aValue;
//		        fireTableCellUpdated(rowIndex, columnIndex);
//		    }
		}

		 
		   
		// only allow the first column to be editable, this is the column  
		// with our checkboxes  
		public boolean isCellEditable(int rowIndex, int columnIndex) {  
		return (columnIndex == 0 || columnIndex==9);  
		}  
		} 
	public class CheckBoxCellEditor extends AbstractCellEditor implements TableCellEditor {

		protected JCheckBox checkBox;;

		public CheckBoxCellEditor() {
		checkBox = new JCheckBox();
		checkBox.setHorizontalAlignment(SwingConstants.CENTER);
		checkBox.setBackground( Color.white);

		}

		public Component getTableCellEditorComponent(
		JTable table, 
		Object value, 
		boolean isSelected, 
		int row, 
		int column) {

		if(column==0 || column==9)
		{
		checkBox.setSelected(((Boolean) value).booleanValue());

		Component c =table.getDefaultRenderer(String.class).getTableCellRendererComponent(table, value, isSelected, false, row, column);

		if (c != null) {
	checkBox.setBackground(c.getBackground());
		}
		}


		return checkBox;

		}


		public Object getCellEditorValue() {
		return new Boolean(checkBox.isSelected());



		}





		}
}
